<template>
  <div class="cx-photo">
    <div class="photo-grid">
      <!-- 照片列表 -->
      <div 
        v-for="(photo, index) in photoList" 
        :key="photo.netId || index"
        class="photo-item"
        @click="handlePhotoClick(photo)"
      >
        <img 
          :src="photo.url" 
          class="photo-img"
          alt="照片"
        />
        
        <!-- 上传进度 -->
        <div v-if="photo.progress !== undefined && photo.progress < 1" class="photo-progress">
          <el-progress 
            type="circle" 
            :percentage="Math.round((photo.progress || 0) * 100)"
            :width="60"
          />
          <span class="progress-text">{{ Math.round((photo.progress || 0) * 100) }}%</span>
        </div>
        
        <!-- 操作遮罩 -->
        <div v-if="editable" class="photo-mask">
          <div class="photo-actions">
            <el-button 
              type="danger" 
              icon="el-icon-delete" 
              circle 
              size="small"
              @click.stop="handleDelete(photo)"
            />
          </div>
        </div>
      </div>
      
      <!-- 上传按钮 -->
      <div 
        v-if="editable"
        class="photo-item upload-btn"
        @click="handleUpload"
      >
        <i class="el-icon-plus upload-icon"></i>
        <span class="upload-text">上传照片</span>
      </div>
    </div>
    
    <!-- 图片预览对话框 -->
    <el-image-viewer
      v-if="showViewer"
      :url-list="imageUrls"
      :initial-index="currentIndex"
      @close="showViewer = false"
    />
    
    <!-- 隐藏的文件输入 -->
    <input
      ref="fileInput"
      type="file"
      accept="image/*"
      multiple
      style="display: none"
      @change="handleFileChange"
    />
  </div>
</template>

<script>
/**
 * 组件名称: Photo (Element UI 版本)
 * 功能说明: 照片上传和查看组件
 * 研发时间: 2025/11/17
 * 研发人员: AI Assistant
 */

export default {
  name: 'Photo',
  
  props: {
    editable: {
      type: Boolean,
      default: true
    },
    controller: {
      type: Object,
      required: true
    },
    busType: {
      type: String,
      default: '0'
    },
    showDownLoadBtn: {
      type: Boolean,
      default: false
    },
    isCompress: {
      type: Boolean,
      default: false
    }
  },
  
  data() {
    return {
      photoList: [],
      showViewer: false,
      currentIndex: 0,
      uploadProgressListener: null
    }
  },
  
  computed: {
    currentPhotoList() {
      if (this.controller && typeof this.controller.getPhotoList === 'function') {
        return this.controller.getPhotoList(this.busType)
      }
      return []
    },
    
    imageUrls() {
      return this.photoList.map(p => p.url)
    }
  },
  
  created() {
    this.initComponent()
  },
  
  beforeUnmount() {
    if (this.controller && this.uploadProgressListener) {
      this.controller.removeUploadProgressListener(this.uploadProgressListener)
    }
  },
  
  methods: {
    initComponent() {
      this.updatePhotoList()
      this.bindControllerEvents()
    },
    
    bindControllerEvents() {
      if (this.controller && typeof this.controller === 'object') {
        this.uploadProgressListener = (fileBean, progress) => {
          const photoIndex = this.photoList.findIndex(p => p.url === fileBean.url)
          if (photoIndex !== -1) {
            this.$set(this.photoList[photoIndex], 'progress', progress)
          }
        }
        
        if (typeof this.controller.addUploadProgressListener === 'function') {
          this.controller.addUploadProgressListener(this.uploadProgressListener)
        }
      }
    },
    
    updatePhotoList() {
      const newPhotoList = this.currentPhotoList
      this.photoList = newPhotoList.map(photo => {
        const newPhoto = { ...photo }
        if (newPhoto.progress === undefined) {
          this.$set(newPhoto, 'progress', 1)
        }
        return newPhoto
      })
    },
    
    handleUpload() {
      if (!this.editable) return
      this.$refs.fileInput.click()
    },
    
    async handleFileChange(event) {
      const files = Array.from(event.target.files)
      if (files.length === 0) return
      
      for (const file of files) {
        await this.uploadSingleImage(file)
      }
      
      // 清空input
      event.target.value = ''
    },
    
    async uploadSingleImage(file) {
      try {
        // 创建临时URL用于预览
        const tempUrl = URL.createObjectURL(file)
        
        const title = typeof this.controller.getTitle === 'function'
          ? this.controller.getTitle({}, this.busType)
          : `photo_${Date.now()}`
        
        const fileBean = {
          title: title || `photo_${Date.now()}`,
          userRawTitle: !!title,
          url: tempUrl,
          file: file,
          busType: this.busType,
          mediaType: 'PIC',
          memo: this.controller.memo || '',
          task: this.controller.task || '',
          progress: 0,
          netId: 0
        }
        
        this.$set(fileBean, 'progress', 0)
        
        // 通过 controller 方法添加文件，避免直接修改 prop
        if (typeof this.controller.addFile === 'function') {
          this.controller.addFile(fileBean)
        } else if (this.controller.fileList && Array.isArray(this.controller.fileList)) {
          // 如果没有 addFile 方法，通过事件通知父组件
          this.$emit('file-add', fileBean)
        }
        
        this.updatePhotoList()
        
        // 上传文件
        if (typeof this.controller.uploadFile === 'function') {
          await this.controller.uploadFile(
            this.controller.entityId,
            fileBean,
            this.handleUploadSuccess,
            {}
          )
        }
        
        this.$emit('upload-complete', fileBean)
      } catch (error) {
        this.$message.error('上传图片失败: ' + error.message)
        console.error('上传图片失败:', error)
      }
    },
    
    handlePhotoClick(photo) {
      this.currentIndex = this.photoList.findIndex(p => p.url === photo.url)
      this.showViewer = true
      this.$emit('photo-selected', photo)
    },
    
    async handleDelete(photo) {
      try {
        await this.$confirm('确定要删除这张照片吗？', '确认删除', {
          type: 'warning'
        })
        
        if (this.controller && typeof this.controller.delFile === 'function') {
          await this.controller.delFile(photo, {})
          this.$emit('photo-deleted', photo)
          this.$message.success('删除成功')
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败: ' + error.message)
        }
      }
    },
    
    handleUploadSuccess(result) {
      console.log('照片上传成功:', result)
    }
  }
}
</script>

<style lang="scss" scoped>
.cx-photo {
  padding: 10px;
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 15px;
}

.photo-item {
  position: relative;
  width: 100%;
  aspect-ratio: 1;
  border-radius: 5px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}

.photo-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.photo-progress {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.progress-text {
  color: white;
  font-size: 12px;
  margin-top: 5px;
}

.upload-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  border: 2px dashed #dee2e6;
  border-radius: 5px;
  color: #6c757d;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    border-color: #409eff;
    color: #409eff;
    background: #ecf5ff;
  }
}

.upload-icon {
  font-size: 24px;
  margin-bottom: 5px;
}

.upload-text {
  font-size: 12px;
}

.photo-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  
  .photo-item:hover & {
    opacity: 1;
  }
}

.photo-actions {
  display: flex;
  gap: 10px;
}
</style>
